package com.lovepick.http;

import java.util.Map;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

import com.lovepick.GlobalApp;
import com.lovepick.MainActivity;
import com.lovepick.MsgActivity;
import com.lovepick.R;
import com.lovepick.database.MsgListTable;
import com.lovepick.fragment.MsgFragment;
import com.lovepick.util.BaseUtils;
import com.lovepick.util.Constant;


public class GetNewMsgService extends Service
{
	private final String TAG = "GetNewMsgService";

	// 点击查看
	private Intent mIntent = null;
	private PendingIntent mPendingIntent = null;

	// 通知栏消息
	public static final int NOTIFY_ID = 0x1000;
	private static boolean mIsChatOn = false;
	private static boolean mIsMainOn = true;
	private int mNumMsgs = 0;
	private int mUserID = 0;
	private NotificationCompat.Builder mBuilder = null;
	private NotificationManager mNotificationManager = null;
	private TaskStackBuilder mStackBuilder = null;

	private MsgThread mThread = null;
	private MsgShowReciver mReciver = null;

	@Override
	public void onCreate()
	{
		Log.i(TAG, "msg service create");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		Log.i(TAG, "service start");

		// 服务启动时注册广播
		Log.i(TAG, "注册会话界面开启的接收广播");
		IntentFilter msgFilter = new IntentFilter(Constant.ACTION_MSG_SHOW);
		//IntentFilter mainFilter = new IntentFilter(Constant.ACTION_MAIN_ON);
		mReciver = new MsgShowReciver();
		registerReceiver(mReciver, msgFilter);
		//registerReceiver(mReciver, mainFilter);

		//mIntent = new Intent(GetNewMsgService.this, MsgListActivity.class);
		mStackBuilder = TaskStackBuilder.create(this);
		//mStackBuilder.addParentStack(MsgListActivity.class);

		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		mBuilder = new NotificationCompat.Builder(this);

		// 开启获取新消息的线程
		mThread = new MsgThread();
		mThread.isRunning = true;
		mThread.start();

		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public IBinder onBind(Intent arg0)
	{
		// TODO Auto-generated method stub
		return null;
	}

	private void showNotification(Map<String, Object> map)
	{
		Log.i(TAG, "通知栏显示新消息通知");
		int numbers = 0;
		String contentTitle = "";
		String contentText = "";
		int userID = 0;
		int flag = (Integer)map.get("flag");

		switch (flag)
		{
			case 0:
				// 只有一个用户发来消息
				contentTitle = (String) map.get("nick_names");
				contentText = (String) map.get("last_msg");
				numbers = (Integer) map.get("number");
				userID = (Integer) map.get("user_id");
				break;

			case 1:
				// 有多个用户发来消息
				contentTitle = getString(R.string.new_msgs);
				contentText = (String) map.get("nick_names");
				numbers = (Integer) map.get("number");
				break;

			default:
				break;
		}

		Bundle bundle = new Bundle();

		if (flag == 0)
		{
			mIntent = new Intent(this, MsgActivity.class);
			bundle.putInt(MsgFragment.ARG_USERID, userID);
			bundle.putString(MsgFragment.ARG_NICKNAME, (String) map.get("nick_names"));
		}
		else
		{
			mIntent = new Intent(this, MainActivity.class);
			bundle.putString("new_msg", "new_msg");
		}
		mIntent.putExtra("bundle_msg", bundle);

		mStackBuilder.addNextIntent(mIntent);
		mPendingIntent = mStackBuilder.getPendingIntent(0,
				PendingIntent.FLAG_UPDATE_CURRENT);

		mBuilder.setContentTitle(contentTitle);
		mBuilder.setContentText(contentText);
		mBuilder.setSmallIcon(R.drawable.ic_msg_light);
		mBuilder.setContentIntent(mPendingIntent);
		mBuilder.setAutoCancel(true);

		mNumMsgs = GlobalApp.getInstance().getNumMsgNew();
		mNumMsgs += numbers;
		mBuilder.setNumber(mNumMsgs);
		GlobalApp.getInstance().setNumMsgNew(mNumMsgs);
		mNotificationManager.notify(NOTIFY_ID, mBuilder.build());

		Log.i(TAG, "未读消息数目:" + mNumMsgs);
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		Log.i(TAG, "msg service destroy");
		if (mThread != null)
		{
			mThread.isRunning = false;
		}
		// 服务销毁时反注册广播
		Log.i(TAG, "反注册会话界面开启的接收广播");
		unregisterReceiver(mReciver);

		System.exit(0);
	}

	/**
	 * <p>
	 * 从服务器获取新消息的线程, 每隔 10s 请求一次服务器;
	 * </p>
	 * <p>
	 * 若有新消息则通知.
	 * <p>
	 *
	 * @author Liutong
	 *
	 */
	private class MsgThread extends Thread
	{
		private final String THREAD_TAG = "MsgThread";
		/**
		 * 标识线程的运行状态
		 */
		public boolean isRunning = true;

		@Override
		public void run()
		{
			Log.i(THREAD_TAG, "-----MsgThread start-----");
			while (isRunning)
			{
				try
				{
					// 从服务器获取新消息
					Log.i(TAG, "###get new msgs###");
					double random = Math.random();
					String url = Constant.HTTP_URL_GET_NEW_MSG;
					String _r = String.valueOf(random);
					url += "&_r=" + _r;
					url += "&LastID=" + GlobalApp.getInstance().getLastID();
					HttpHelper httpHelper = new HttpHelper();
					String result = httpHelper.doGet(url);

					mUserID = mIsChatOn ? mUserID : -1;
					boolean hasNewMsgs = BaseUtils.saveNewMsgs(result, mUserID);

					Log.i(THREAD_TAG, "###检测MsgActivity是否开启###" + mIsChatOn);
					if (hasNewMsgs)
					{
						Intent intent = new Intent(Constant.ACTION_NEW_MSGS);
						sendBroadcast(intent);

						/*if (!notify.isEmpty() && !mIsMainOn)
						{
							// 通知栏提示
							showNotification(notify);
						}*/
					}
				}
				catch (Exception e)
				{
					// TODO: handle exception
					Log.i(TAG, e.getCause().toString());
					e.printStackTrace();
					continue;
				}
				finally
				{
					try
					{
						Thread.sleep(7000);
					}
					catch (InterruptedException e)
					{
						// TODO Auto-generated catch block
						Log.i(TAG, e.getCause().toString());
						e.printStackTrace();
						continue;
					}
				}

			}
			// 线程运行标识被设置为false, 线程终止运行
		}

	}


	private class MsgShowReciver extends BroadcastReceiver
	{

		@Override
		public void onReceive(Context context, Intent intent)
		{
			// TODO Auto-generated method stub

			if (Constant.ACTION_MSG_SHOW.equals(intent.getAction()))
			{
				Log.i(TAG, "接收到MsgActivity发送的广播");
				mIsChatOn = intent.getBundleExtra("bundle").getBoolean("flag");
				Log.i(TAG, "mIsChatOn=" + mIsChatOn);
				mUserID = intent.getBundleExtra("bundle").getInt(MsgListTable.USER_ID);
				Log.i(TAG, "mUserID=" + mUserID);
			}
			else if (Constant.ACTION_MAIN_ON.equals(intent.getAction())) {
				Log.i(TAG, "接收到MainActivity发送的广播");
				mIsMainOn = intent.getBundleExtra("bundle").getBoolean("flag");
				Log.i(TAG, "mIsMainOn=" + mIsMainOn);
			}
		}

	}

}
